<!DOCTYPE html>
<html>
  <head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
  <meta name="description" content="刘清政">
  <meta name="keyword" content="hexo-theme">
  
    <link rel="shortcut icon" href="/css/images/logo.png">
  
  <title>
    
      python/Django框架/6-视图层 | Justin-刘清政的博客
    
  </title>
  <link href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <link href="//cdnjs.cloudflare.com/ajax/libs/nprogress/0.2.0/nprogress.min.css" rel="stylesheet">
  <link href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/tomorrow.min.css" rel="stylesheet">
  
<link rel="stylesheet" href="/css/style.css">

  
    
<link rel="stylesheet" href="/css/plugins/gitment.css">

  
  <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/geopattern/1.2.3/js/geopattern.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/nprogress/0.2.0/nprogress.min.js"></script>
  
    
<script src="/js/qrious.js"></script>

  
  
    
<script src="/js/gitment.js"></script>

  
  

  
<meta name="generator" content="Hexo 4.2.0"></head>
<div class="wechat-share">
  <img src="/css/images/logo.png" />
</div>

  <body>
    <header class="header fixed-header">
  <div class="header-container">
    <a class="home-link" href="/">
      <div class="logo"></div>
      <span>Justin-刘清政的博客</span>
    </a>
    <ul class="right-list">
      
        <li class="list-item">
          
            <a href="/" class="item-link">主页</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/tags/" class="item-link">标签</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/archives/" class="item-link">归档</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/about/" class="item-link">关于我</a>
          
        </li>
      
    </ul>
    <div class="menu">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </div>
    <div class="menu-mask">
      <ul class="menu-list">
        
          <li class="menu-item">
            
              <a href="/" class="menu-link">主页</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/tags/" class="menu-link">标签</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/archives/" class="menu-link">归档</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/about/" class="menu-link">关于我</a>
            
          </li>
        
      </ul>
    </div>
  </div>
</header>

    <div id="article-banner">
  <h2>python/Django框架/6-视图层</h2>



  <p class="post-date">2020-09-24</p>
    <!-- 不蒜子统计 -->
    <span id="busuanzi_container_page_pv" style='display:none' class="">
        <i class="icon-smile icon"></i> 阅读数：<span id="busuanzi_value_page_pv"></span>次
    </span>
  <div class="arrow-down">
    <a href="javascript:;"></a>
  </div>
</div>
<main class="app-body flex-box">
  <!-- Article START -->
  <article class="post-article">
    <section class="markdown-content"><h2 id="1-视图函数"><a href="#1-视图函数" class="headerlink" title="1 视图函数"></a><strong>1 视图函数</strong></h2><p>一个视图函数，简称视图，是一个简单的Python 函数，它接受Web请求并且返回Web响应。响应可以是一张网页的HTML内容，一个重定向，一个404错误，一个XML文档，或者一张图片. . . 是任何东西都可以。无论视图本身包含什么逻辑，都要返回响应。代码写在哪里也无所谓，只要它在你的Python目录下面。除此之外没有更多的要求了——可以说“没有什么神奇的地方”。为了将代码放在某处，约定是将视图放置在项目或应用程序目录中的名为<code>views.py</code>的文件中。</p>
<p>下面是一个返回当前日期和时间作为HTML文档的视图：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> django.shortcuts <span class="keyword">import</span> render, HttpResponse, HttpResponseRedirect, redirect</span><br><span class="line"><span class="keyword">import</span> datetime</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">current_datetime</span><span class="params">(request)</span>:</span></span><br><span class="line">    now = datetime.datetime.now()</span><br><span class="line">    html = <span class="string">"&lt;html&gt;&lt;body&gt;It is now %s.&lt;/body&gt;&lt;/html&gt;"</span> % now</span><br><span class="line">    <span class="keyword">return</span> HttpResponse(html)</span><br></pre></td></tr></table></figure>



<p>让我们逐行阅读上面的代码：</p>
<ul>
<li><p>首先，我们从 <code>django.shortcuts</code>模块导入了<code>HttpResponse</code>类，以及Python的<code>datetime</code>库。</p>
</li>
<li><p>接着，我们定义了<code>current_datetime</code>函数。它就是视图函数。每个视图函数都使用<code>HttpRequest</code>对象作为第一个参数，并且通常称之为<code>request</code>。</p>
<p>注意,视图函数的名称并不重要；不需要用一个统一的命名方式来命名，以便让Django识别它。我们将其命名为<code>current_datetime</code>，是因为这个名称能够精确地反映出它的功能。</p>
</li>
<li><p>这个视图会返回一个<code>HttpResponse</code>对象，其中包含生成的响应。每个视图函数都负责返回一个<code>HttpResponse</code>对象。</p>
</li>
</ul>
<img src="https://tva1.sinaimg.cn/large/007S8ZIlgy1gj1wn5vy67j30r40ekafx.jpg" alt="image-20200924181344700" style="zoom:50%;" />

<p><strong>视图层，熟练掌握两个对象即可：请求对象(request)和响应对象(HttpResponse)</strong></p>
<h2 id="2-HttpRequest对象"><a href="#2-HttpRequest对象" class="headerlink" title="2 HttpRequest对象"></a>2 HttpRequest对象</h2><h3 id="request属性"><a href="#request属性" class="headerlink" title="request属性"></a>request属性</h3><p>django将请求报文中的请求行、首部信息、内容主体封装成 HttpRequest 类中的属性。 除了特殊说明的之外，其他均为只读的</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">'''</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">1.HttpRequest.GET</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">　　一个类似于字典的对象，包含 HTTP GET 的所有参数。详情请参考 QueryDict 对象。</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">2.HttpRequest.POST</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">　　一个类似于字典的对象，如果请求中包含表单数据，则将这些数据封装成 QueryDict 对象。</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">　　POST 请求可以带有空的 POST 字典 —— 如果通过 HTTP POST 方法发送一个表单，但是表单中没有任何的数据，QueryDict 对象依然会被创建。</span></span><br><span class="line"><span class="string">   因此，不应该使用 if request.POST  来检查使用的是否是POST 方法；应该使用 if request.method == "POST"</span></span><br><span class="line"><span class="string">　　另外：如果使用 POST 上传文件的话，文件信息将包含在 FILES 属性中。</span></span><br><span class="line"><span class="string">   </span></span><br><span class="line"><span class="string">   注意：键值对的值是多个的时候,比如checkbox类型的input标签，select标签，需要用：</span></span><br><span class="line"><span class="string">        request.POST.getlist("hobby")</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">3.HttpRequest.body</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">　　一个字符串，代表请求报文的主体。在处理非 HTTP 形式的报文时非常有用，例如：二进制图片、XML,Json等。</span></span><br><span class="line"><span class="string">　　但是，如果要处理表单数据的时候，推荐还是使用 HttpRequest.POST 。</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">4.HttpRequest.path</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">　　一个字符串，表示请求的路径组件（不含域名）。</span></span><br><span class="line"><span class="string">　　例如："/music/bands/the_beatles/"</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">5.HttpRequest.method</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">　　一个字符串，表示请求使用的HTTP 方法。必须使用大写。</span></span><br><span class="line"><span class="string">　　例如："GET"、"POST"</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">6.HttpRequest.encoding</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">　　一个字符串，表示提交的数据的编码方式（如果为 None 则表示使用 DEFAULT_CHARSET 的设置，默认为 'utf-8'）。</span></span><br><span class="line"><span class="string">   这个属性是可写的，你可以修改它来修改访问表单数据使用的编码。</span></span><br><span class="line"><span class="string">   接下来对属性的任何访问（例如从 GET 或 POST 中读取数据）将使用新的 encoding 值。</span></span><br><span class="line"><span class="string">   如果你知道表单数据的编码不是 DEFAULT_CHARSET ，则使用它。</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">7.HttpRequest.META</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string"> 　　一个标准的Python 字典，包含所有的HTTP 首部。具体的头部信息取决于客户端和服务器，下面是一些示例：</span></span><br><span class="line"><span class="string">　　取值：</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">    CONTENT_LENGTH —— 请求的正文的长度（是一个字符串）。</span></span><br><span class="line"><span class="string">    CONTENT_TYPE —— 请求的正文的MIME 类型。</span></span><br><span class="line"><span class="string">    HTTP_ACCEPT —— 响应可接收的Content-Type。</span></span><br><span class="line"><span class="string">    HTTP_ACCEPT_ENCODING —— 响应可接收的编码。</span></span><br><span class="line"><span class="string">    HTTP_ACCEPT_LANGUAGE —— 响应可接收的语言。</span></span><br><span class="line"><span class="string">    HTTP_HOST —— 客服端发送的HTTP Host 头部。</span></span><br><span class="line"><span class="string">    HTTP_REFERER —— Referring 页面。</span></span><br><span class="line"><span class="string">    HTTP_USER_AGENT —— 客户端的user-agent 字符串。</span></span><br><span class="line"><span class="string">    QUERY_STRING —— 单个字符串形式的查询字符串（未解析过的形式）。</span></span><br><span class="line"><span class="string">    REMOTE_ADDR —— 客户端的IP 地址。</span></span><br><span class="line"><span class="string">    REMOTE_HOST —— 客户端的主机名。</span></span><br><span class="line"><span class="string">    REMOTE_USER —— 服务器认证后的用户。</span></span><br><span class="line"><span class="string">    REQUEST_METHOD —— 一个字符串，例如"GET" 或"POST"。</span></span><br><span class="line"><span class="string">    SERVER_NAME —— 服务器的主机名。</span></span><br><span class="line"><span class="string">    SERVER_PORT —— 服务器的端口（是一个字符串）。</span></span><br><span class="line"><span class="string"> 　　从上面可以看到，除 CONTENT_LENGTH 和 CONTENT_TYPE 之外，请求中的任何 HTTP 首部转换为 META 的键时，</span></span><br><span class="line"><span class="string">    都会将所有字母大写并将连接符替换为下划线最后加上 HTTP_  前缀。</span></span><br><span class="line"><span class="string">    所以，一个叫做 X-Bender 的头部将转换成 META 中的 HTTP_X_BENDER 键。</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">8.HttpRequest.FILES</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">　　一个类似于字典的对象，包含所有的上传文件信息。</span></span><br><span class="line"><span class="string">   FILES 中的每个键为&lt;input type="file" name="" /&gt; 中的name，值则为对应的数据。</span></span><br><span class="line"><span class="string">　　注意，FILES 只有在请求的方法为POST 且提交的&lt;form&gt; 带有enctype="multipart/form-data" 的情况下才会</span></span><br><span class="line"><span class="string">   包含数据。否则，FILES 将为一个空的类似于字典的对象。</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">9.HttpRequest.COOKIES</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">　　一个标准的Python 字典，包含所有的cookie。键和值都为字符串。</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">10.HttpRequest.session</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string"> 　　一个既可读又可写的类似于字典的对象，表示当前的会话。只有当Django 启用会话的支持时才可用。</span></span><br><span class="line"><span class="string">    完整的细节参见会话的文档。</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">11.HttpRequest.user(用户认证组件下使用)</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">　　一个 AUTH_USER_MODEL 类型的对象，表示当前登录的用户。</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">　　如果用户当前没有登录，user 将设置为 django.contrib.auth.models.AnonymousUser 的一个实例。你可以通过 is_authenticated() 区分它们。</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">    例如：</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">    if request.user.is_authenticated():</span></span><br><span class="line"><span class="string">        # Do something for logged-in users.</span></span><br><span class="line"><span class="string">    else:</span></span><br><span class="line"><span class="string">        # Do something for anonymous users.</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">     　　user 只有当Django 启用 AuthenticationMiddleware 中间件时才可用。</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">     -------------------------------------------------------------------------------------</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">    匿名用户</span></span><br><span class="line"><span class="string">    class models.AnonymousUser</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">    django.contrib.auth.models.AnonymousUser 类实现了django.contrib.auth.models.User 接口，但具有下面几个不同点：</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">    id 永远为None。</span></span><br><span class="line"><span class="string">    username 永远为空字符串。</span></span><br><span class="line"><span class="string">    get_username() 永远返回空字符串。</span></span><br><span class="line"><span class="string">    is_staff 和 is_superuser 永远为False。</span></span><br><span class="line"><span class="string">    is_active 永远为 False。</span></span><br><span class="line"><span class="string">    groups 和 user_permissions 永远为空。</span></span><br><span class="line"><span class="string">    is_anonymous() 返回True 而不是False。</span></span><br><span class="line"><span class="string">    is_authenticated() 返回False 而不是True。</span></span><br><span class="line"><span class="string">    set_password()、check_password()、save() 和delete() 引发 NotImplementedError。</span></span><br><span class="line"><span class="string">    New in Django 1.8:</span></span><br><span class="line"><span class="string">    新增 AnonymousUser.get_username() 以更好地模拟 django.contrib.auth.models.User。</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">*/</span></span><br></pre></td></tr></table></figure>



<h3 id="request常用方法"><a href="#request常用方法" class="headerlink" title="request常用方法"></a>request常用方法</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">'''</span></span><br><span class="line"><span class="string">1.HttpRequest.get_full_path()</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">　　返回 path，如果可以将加上查询字符串。</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">　　例如："/music/bands/the_beatles/?print=true"</span></span><br><span class="line"><span class="string">　　注意和path的区别：http://127.0.0.1:8001/order/?name=lqz&amp;age=10</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">2.HttpRequest.is_ajax()</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">　　如果请求是通过XMLHttpRequest 发起的，则返回True，方法是检查 HTTP_X_REQUESTED_WITH 相应的首部是否是字符串'XMLHttpRequest'。</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">　　大部分现代的 JavaScript 库都会发送这个头部。如果你编写自己的 XMLHttpRequest 调用（在浏览器端），你必须手工设置这个值来让 is_ajax() 可以工作。</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">　　如果一个响应需要根据请求是否是通过AJAX 发起的，并且你正在使用某种形式的缓存例如Django 的 cache middleware，</span></span><br><span class="line"><span class="string">   你应该使用 vary_on_headers('HTTP_X_REQUESTED_WITH') 装饰你的视图以让响应能够正确地缓存。</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">'''</span></span><br></pre></td></tr></table></figure>



<h2 id="3-HttpResponse对象"><a href="#3-HttpResponse对象" class="headerlink" title="3 HttpResponse对象"></a>3 HttpResponse对象</h2><p>响应对象主要有三种形式：</p>
<ul>
<li>HttpResponse()</li>
<li>render()</li>
<li>redirect()</li>
</ul>
<p>HttpResponse()括号内直接跟一个具体的字符串作为响应体，比较直接很简单，所以这里主要介绍后面两种形式。</p>
<h3 id="render"><a href="#render" class="headerlink" title="render()"></a>render()</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">render(request, template_name[, context]）`  `结合一个给定的模板和一个给定的上下文字典，并返回一个渲染后的 HttpResponse 对象。</span><br><span class="line">参数：</span><br><span class="line">     request： 用于生成响应的请求对象。</span><br><span class="line"></span><br><span class="line">     template_name：要使用的模板的完整名称，可选的参数</span><br><span class="line"></span><br><span class="line">     context：添加到模板上下文的一个字典。默认是一个空字典。如果字典中的某个值是可调用的，视图将在渲染模板之前调用它。</span><br><span class="line"></span><br><span class="line">render方法就是将一个模板页面中的模板语法进行渲染，最终渲染成一个html页面作为响应体。</span><br></pre></td></tr></table></figure>

<h3 id="redirect"><a href="#redirect" class="headerlink" title="redirect()"></a>redirect()</h3><p>传递要重定向的一个硬编码的URL</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">my_view</span><span class="params">(request)</span>:</span></span><br><span class="line">    ...</span><br><span class="line">    <span class="keyword">return</span> redirect(<span class="string">'/some/url/'</span>)</span><br></pre></td></tr></table></figure>

<p>也可以是一个完整的URL：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">my_view</span><span class="params">(request)</span>:</span></span><br><span class="line">    ...</span><br><span class="line">    <span class="keyword">return</span> redirect(<span class="string">'http://www.baidu.com/'</span>)</span><br></pre></td></tr></table></figure>

<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span>）<span class="number">301</span>和<span class="number">302</span>的区别。</span><br><span class="line"></span><br><span class="line">　　<span class="number">301</span>和<span class="number">302</span>状态码都表示重定向，就是说浏览器在拿到服务器返回的这个状态码后会自动跳转到一个新的URL地址，这个地址可以从响应的Location首部中获取</span><br><span class="line">  （用户看到的效果就是他输入的地址A瞬间变成了另一个地址B）——这是它们的共同点。</span><br><span class="line"></span><br><span class="line">　　他们的不同在于。<span class="number">301</span>表示旧地址A的资源已经被永久地移除了（这个资源不可访问了），搜索引擎在抓取新内容的同时也将旧的网址交换为重定向之后的网址；</span><br><span class="line"></span><br><span class="line">　　<span class="number">302</span>表示旧地址A的资源还在（仍然可以访问），这个重定向只是临时地从旧地址A跳转到地址B，搜索引擎会抓取新的内容而保存旧的网址。 SEO302好于<span class="number">301</span></span><br><span class="line"></span><br><span class="line"> </span><br><span class="line"></span><br><span class="line"><span class="number">2</span>）重定向原因：</span><br><span class="line">（<span class="number">1</span>）网站调整（如改变网页目录结构）；</span><br><span class="line">（<span class="number">2</span>）网页被移到一个新地址；</span><br><span class="line">（<span class="number">3</span>）网页扩展名改变(如应用需要把.php改成.Html或.shtml)。</span><br><span class="line">        这种情况下，如果不做重定向，则用户收藏夹或搜索引擎数据库中旧地址只能让访问客户得到一个<span class="number">404</span>页面错误信息，访问流量白白丧失；再者某些注册了多个域名的</span><br><span class="line">    网站，也需要通过重定向让访问这些域名的用户自动跳转到主站点等。</span><br></pre></td></tr></table></figure>



<h2 id="4-JsonResponse"><a href="#4-JsonResponse" class="headerlink" title="4 JsonResponse"></a>4 JsonResponse</h2><p>向前端返回一个json格式字符串的两种方式</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 第一种方式</span></span><br><span class="line"><span class="comment"># import json</span></span><br><span class="line"><span class="comment"># data=&#123;'name':'lqz','age':18&#125;</span></span><br><span class="line"><span class="comment"># data1=['lqz','egon']</span></span><br><span class="line"><span class="comment"># return HttpResponse(json.dumps(data1))</span></span><br><span class="line"><span class="comment"># 第二种方式</span></span><br><span class="line"><span class="keyword">from</span> django.http <span class="keyword">import</span> JsonResponse</span><br><span class="line"><span class="comment"># data = &#123;'name': 'lqz', 'age': 18&#125;</span></span><br><span class="line">data1 = [<span class="string">'lqz'</span>, <span class="string">'egon'</span>]</span><br><span class="line"><span class="comment"># return JsonResponse(data)</span></span><br><span class="line"><span class="keyword">return</span> JsonResponse(data1,safe=<span class="literal">False</span>)</span><br></pre></td></tr></table></figure>



<h2 id="5-CBV和FBV"><a href="#5-CBV和FBV" class="headerlink" title="5 CBV和FBV"></a>5 CBV和FBV</h2><p><strong>CBV基于类的视图(Class base view)和FBV基于函数的视图（Function base view）</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> django.views <span class="keyword">import</span> View</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">AddPublish</span><span class="params">(View)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">dispatch</span><span class="params">(self, request, *args, **kwargs)</span>:</span></span><br><span class="line">        print(request)</span><br><span class="line">        print(args)</span><br><span class="line">        print(kwargs)</span><br><span class="line">        <span class="comment"># 可以写类似装饰器的东西，在前后加代码</span></span><br><span class="line">        obj=super().dispatch(request, *args, **kwargs)</span><br><span class="line">        <span class="keyword">return</span> obj</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">get</span><span class="params">(self,request)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> render(request,<span class="string">'index.html'</span>)</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">post</span><span class="params">(self,request)</span>:</span></span><br><span class="line">        request</span><br><span class="line">        <span class="keyword">return</span> HttpResponse(<span class="string">'post'</span>)</span><br></pre></td></tr></table></figure>



<h2 id="6-简单文件上传"><a href="#6-简单文件上传" class="headerlink" title="6 简单文件上传"></a>6 简单文件上传</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">print(request.FILES)</span><br><span class="line">print(type(request.FILES.get(<span class="string">'file_name'</span>)))</span><br><span class="line"></span><br><span class="line">file_name=request.FILES.get(<span class="string">'file_name'</span>).name</span><br><span class="line"><span class="keyword">from</span> django.core.files.uploadedfile <span class="keyword">import</span> InMemoryUploadedFile</span><br><span class="line"><span class="keyword">with</span> open(file_name,<span class="string">'wb'</span>)<span class="keyword">as</span> f:</span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> request.FILES.get(<span class="string">'file_name'</span>).chunks():</span><br><span class="line">        f.write(i)</span><br></pre></td></tr></table></figure>

</section>
    <!-- Tags START -->
    
    <!-- Tags END -->
    <!-- NAV START -->
    
  <div class="nav-container">
    <!-- reverse left and right to put prev and next in a more logic postition -->
    
      <a class="nav-left" href="/python/Django%E6%A1%86%E6%9E%B6/19-Django%E9%AB%98%E7%BA%A7%E4%B9%8B-%E7%BC%93%E5%AD%98/">
        <span class="nav-arrow">← </span>
        
          python/Django框架/19-Django高级之-缓存
        
      </a>
    
    
      <a class="nav-right" href="/python/Django%E6%A1%86%E6%9E%B6/21-Django%E9%AB%98%E7%BA%A7%E4%B9%8B-%E8%B7%A8%E7%AB%99%E8%AF%B7%E6%B1%82%E4%BC%AA%E9%80%A0/">
        
          python/Django框架/21-Django高级之-跨站请求伪造
        
        <span class="nav-arrow"> →</span>
      </a>
    
  </div>

    <!-- NAV END -->
    <!-- 打赏 START -->
    
      <div class="money-like">
        <div class="reward-btn">
          赏
          <span class="money-code">
            <span class="alipay-code">
              <div class="code-image"></div>
              <b>使用支付宝打赏</b>
            </span>
            <span class="wechat-code">
              <div class="code-image"></div>
              <b>使用微信打赏</b>
            </span>
          </span>
        </div>
        <p class="notice">点击上方按钮,请我喝杯咖啡！</p>
      </div>
    
    <!-- 打赏 END -->
    <!-- 二维码 START -->
    
      <div class="qrcode">
        <canvas id="share-qrcode"></canvas>
        <p class="notice">扫描二维码，分享此文章</p>
      </div>
    
    <!-- 二维码 END -->
    
      <!-- Gitment START -->
      <div id="comments"></div>
      <!-- Gitment END -->
    
  </article>
  <!-- Article END -->
  <!-- Catalog START -->
  
    <aside class="catalog-container">
  <div class="toc-main">
  <!-- 不蒜子统计 -->
    <strong class="toc-title">目录</strong>
    
      <ol class="toc-nav"><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#1-视图函数"><span class="toc-nav-text">1 视图函数</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#2-HttpRequest对象"><span class="toc-nav-text">2 HttpRequest对象</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#request属性"><span class="toc-nav-text">request属性</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#request常用方法"><span class="toc-nav-text">request常用方法</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#3-HttpResponse对象"><span class="toc-nav-text">3 HttpResponse对象</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#render"><span class="toc-nav-text">render()</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#redirect"><span class="toc-nav-text">redirect()</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#4-JsonResponse"><span class="toc-nav-text">4 JsonResponse</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#5-CBV和FBV"><span class="toc-nav-text">5 CBV和FBV</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#6-简单文件上传"><span class="toc-nav-text">6 简单文件上传</span></a></li></ol>
    
  </div>
</aside>
  
  <!-- Catalog END -->
</main>

<script>
  (function () {
    var url = 'http://www.liuqingzheng.top/python/Django框架/6-视图层/';
    var banner = ''
    if (banner !== '' && banner !== 'undefined' && banner !== 'null') {
      $('#article-banner').css({
        'background-image': 'url(' + banner + ')'
      })
    } else {
      $('#article-banner').geopattern(url)
    }
    $('.header').removeClass('fixed-header')

    // error image
    $(".markdown-content img").on('error', function() {
      $(this).attr('src', 'http://file.muyutech.com/error-img.png')
      $(this).css({
        'cursor': 'default'
      })
    })

    // zoom image
    $(".markdown-content img").on('click', function() {
      var src = $(this).attr('src')
      if (src !== 'http://file.muyutech.com/error-img.png') {
        var imageW = $(this).width()
        var imageH = $(this).height()

        var zoom = ($(window).width() * 0.95 / imageW).toFixed(2)
        zoom = zoom < 1 ? 1 : zoom
        zoom = zoom > 2 ? 2 : zoom
        var transY = (($(window).height() - imageH) / 2).toFixed(2)

        $('body').append('<div class="image-view-wrap"><div class="image-view-inner"><img src="'+ src +'" /></div></div>')
        $('.image-view-wrap').addClass('wrap-active')
        $('.image-view-wrap img').css({
          'width': `${imageW}`,
          'transform': `translate3d(0, ${transY}px, 0) scale3d(${zoom}, ${zoom}, 1)`
        })
        $('html').css('overflow', 'hidden')

        $('.image-view-wrap').on('click', function() {
          $(this).remove()
          $('html').attr('style', '')
        })
      }
    })
  })();
</script>


  <script>
    var qr = new QRious({
      element: document.getElementById('share-qrcode'),
      value: document.location.href
    });
  </script>



  <script>
    var gitmentConfig = "liuqingzheng";
    if (gitmentConfig !== 'undefined') {
      var gitment = new Gitment({
        id: "python/Django框架/6-视图层",
        owner: "liuqingzheng",
        repo: "FuckBlog",
        oauth: {
          client_id: "32a4076431cf39d0ecea",
          client_secret: "94484bd79b3346a949acb2fda3c8a76ce16990c6"
        },
        theme: {
          render(state, instance) {
            const container = document.createElement('div')
            container.lang = "en-US"
            container.className = 'gitment-container gitment-root-container'
            container.appendChild(instance.renderHeader(state, instance))
            container.appendChild(instance.renderEditor(state, instance))
            container.appendChild(instance.renderComments(state, instance))
            container.appendChild(instance.renderFooter(state, instance))
            return container;
          }
        }
      })
      gitment.render(document.getElementById('comments'))
    }
  </script>




    <div class="scroll-top">
  <span class="arrow-icon"></span>
</div>
    <footer class="app-footer">
<!-- 不蒜子统计 -->
<span id="busuanzi_container_site_pv">
     本站总访问量<span id="busuanzi_value_site_pv"></span>次
</span>
<span class="post-meta-divider">|</span>
<span id="busuanzi_container_site_uv" style='display:none'>
     本站访客数<span id="busuanzi_value_site_uv"></span>人
</span>
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>



  <p class="copyright">
    &copy; 2021 | Proudly powered by <a href="https://www.cnblogs.com/xiaoyuanqujing" target="_blank">小猿取经</a>
    <br>
    Theme by <a href="https://www.cnblogs.com/xiaoyuanqujing" target="_blank" rel="noopener">小猿取经</a>
  </p>
</footer>

<script>
  function async(u, c) {
    var d = document, t = 'script',
      o = d.createElement(t),
      s = d.getElementsByTagName(t)[0];
    o.src = u;
    if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
    s.parentNode.insertBefore(o, s);
  }
</script>
<script>
  async("//cdnjs.cloudflare.com/ajax/libs/fastclick/1.0.6/fastclick.min.js", function(){
    FastClick.attach(document.body);
  })
</script>

<script>
  var hasLine = 'true';
  async("//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js", function(){
    $('figure pre').each(function(i, block) {
      var figure = $(this).parents('figure');
      if (hasLine === 'false') {
        figure.find('.gutter').hide();
      }
      var lang = figure.attr('class').split(' ')[1] || 'code';
      var codeHtml = $(this).html();
      var codeTag = document.createElement('code');
      codeTag.className = lang;
      codeTag.innerHTML = codeHtml;
      $(this).attr('class', '').empty().html(codeTag);
      figure.attr('data-lang', lang.toUpperCase());
      hljs.highlightBlock(block);
    });
  })
</script>





<!-- Baidu Tongji -->

<script>
    var _baId = 'c5fd96eee1193585be191f318c3fa725';
    // Originial
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?" + _baId;
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
</script>


<script src="/js/script.js"></script>


<script src="/js/search.js"></script>


<script src="/js/load.js"></script>



  <span class="local-search local-search-google local-search-plugin" style="right: 50px;top: 70px;;position:absolute;z-index:2;">
      <input type="search" placeholder="站内搜索" id="local-search-input" class="local-search-input-cls" style="">
      <div id="local-search-result" class="local-search-result-cls"></div>
  </span>


  </body>
</html>